<?php

declare(strict_types=1);

namespace App\Exceptions;

use App\Utils\ResultsVo;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Validation\ValidationException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Throwable;

class Handler extends ExceptionHandler
{
    /**
     * A list of the exception types that are not reported.
     *
     * @var array<int, class-string<Throwable>>
     */
    protected $dontReport = [
        \Illuminate\Auth\AuthenticationException::class,
        \Illuminate\Auth\Access\AuthorizationException::class,
        \Symfony\Component\HttpKernel\Exception\HttpException::class,
        \Illuminate\Database\Eloquent\ModelNotFoundException::class,
        \Illuminate\Session\TokenMismatchException::class,
        \Illuminate\Validation\ValidationException::class,
        ServiceException::class,
    ];

    protected $dontFlash = [
        'current_password',
        'password',
        'password_confirmation',
    ];

    public function render($request, Throwable $e): \Symfony\Component\HttpFoundation\Response
    {
        $data = [];
        $data['code'] = 10000;

        switch ($e) {
            case $e instanceof ServiceException:        //throw 异常
                $data['code'] = $e->getCode();
                $data['message'] = $e->getMessage();

                break;

            case $e instanceof ValidationException:     //DTO 验证失败
                $msg = $e->validator->getMessageBag()->toArray();
                $msg = collect($msg)->map(function ($item) {
                    return implode('|', $item);
                })->toArray();
                $data['message'] = implode('', $msg);
                $data['code'] = 20000;

                break;

            case $e instanceof NotFoundHttpException: // 路由验证失败
                $data['message'] = '无效的路由';

                break;
//            case $e instanceof UnauthorizedException;
//                $data['message'] = '无操作权限';
//                break;
            default:
                $data['message'] = '异常: 行:'.$e->getLine().', File '.$e->getFile().',Error '.$e->getMessage();
                // $data['message'] = $e->getMessage();

                break;
        }

        if (false !== strpos($request->path(), getRoutePrefix()) || $request->expectsJson()) {
            return ResultsVo::error($data['message'], $data['code']);
        }

        if (CommonExceptionConstants::NO_LOGIN === $data['code']) {
            // return response()->view('prompt', ['data' => $data]);
        }

        return parent::render($request, $e);
    }
}
